// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <cstdint>
#include <memory>

#include <nebula/csv/options.h>

#include <nebula/types/type_fwd.h>
#include <turbo/base/macros.h>

namespace nebula::csv {

    class BlockParser;

    class TURBO_EXPORT Converter {
    public:
        Converter(const std::shared_ptr<DataType> &type, const ConvertOptions &options,
                  MemoryPool *pool);

        virtual ~Converter() = default;

        virtual turbo::Result<std::shared_ptr<Array>> Convert(const BlockParser &parser,
                                                       int32_t col_index) = 0;

        std::shared_ptr<DataType> type() const { return type_; }

        // create a Converter for the given data type
        static turbo::Result<std::shared_ptr<Converter>> create(
                const std::shared_ptr<DataType> &type, const ConvertOptions &options,
                MemoryPool *pool = default_memory_pool());

    protected:
        TURBO_DISALLOW_COPY_AND_ASSIGN(Converter);

        virtual turbo::Status Initialize() = 0;

        // CAUTION: ConvertOptions can grow large (if it customizes hundreds or
        // thousands of columns), so avoid copying it in each Converter.
        const ConvertOptions &options_;
        MemoryPool *pool_;
        std::shared_ptr<DataType> type_;
    };

    class TURBO_EXPORT DictionaryConverter : public Converter {
    public:
        DictionaryConverter(const std::shared_ptr<DataType> &value_type,
                            const ConvertOptions &options, MemoryPool *pool);

        // If the dictionary length goes above this value, conversion will fail
        // with turbo::out_of_range_error.
        virtual void SetMaxCardinality(int32_t max_length) = 0;

        // create a Converter for the given dictionary value type.
        // The dictionary index type will always be Int32.
        static turbo::Result<std::shared_ptr<DictionaryConverter>> create(
                const std::shared_ptr<DataType> &value_type, const ConvertOptions &options,
                MemoryPool *pool = default_memory_pool());

    protected:
        std::shared_ptr<DataType> value_type_;
    };

}  // namespace nebula::csv
